package com.webserver.controller;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;
import com.webserver.vo.User;

import java.io.*;

/**
 * 用来处理和用户相关的业务操作
 */
public class UserController {
    //保存所有用户信息的目录名字
    private static String userDirName = "./users/";

    static {
        //程序加载时判断一下保存所有用户信息的目录是否存在，不存在先自动创建出来
        File userDir = new File(userDirName);
        if (!userDir.exists()) {
            userDir.mkdirs();
        }
    }

    /**
     * 用来处理用户注册操作
     *
     * @param request
     * @param response
     */
    public void reg(HttpRequest request, HttpResponse response) {
        System.out.println("开始处理用户注册....");
        //1从request中获取用户表单上提交的注册信息
        String username = request.getParameters("username");
        String password = request.getParameters("password");
        String nickname = request.getParameters("nickname");
        String ageStr = request.getParameters("age");
        System.out.println(username + "," + password + "," + nickname + "," + ageStr);
        /*
            必要的验证工作，保证注册的四个信息不能为空，否则直接响应注册失败的提示页面
            失败页面：reg_error.html 居中显示一行字：注册失败，输入信息有误
         */
        if (username == null || password == null || nickname == null || ageStr == null || !ageStr.matches("[0-9]{1,2}")) {
            response.setEntity(new File("./webapps/myweb/reg_error.html"));

            System.out.println("用户注册失败！");
            return;
        }

        /*
            判断是否为重复用户，如果是重复用户则直接响应页面：reg_have_user.html
            该页面居中显示一行字：该用户已存在，请重新注册
         */
        File userFile = new File(userDirName + username + ".obj");
        if (userFile.exists()) {
            response.setEntity(new File("./webapps/myweb/reg_have_user.html"));
            return;
        }


        int age = Integer.parseInt(ageStr);

        //2将该用户信息写入磁盘保存
        User user = new User(username, password, nickname, age);
        try (
                ObjectOutputStream oos = new ObjectOutputStream(
                        new FileOutputStream(userFile)
                );
        ) {
            oos.writeObject(user);
            //注册成功
            response.setEntity(new File("./webapps/myweb/reg_success.html"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        //3设置response响应注册结果页面

        System.out.println("用户注册处理完毕！");
    }
}
